import {createRouter, createWebHistory} from 'vue-router'
import DeviceDetector from "device-detector-js";
import {useLineStore} from "../store/useLineStore";

const components = import.meta.glob(`../**/*.vue`);

const routes = [
  {
    path: '/404',
    name: 'Not - Found',
    meta: {title: "404"},
    component: () => import('../views/404/NotFound.vue'),
  },

  {
    path: '/setting',
    name: 'Setting',
    meta: {title: "设置"},
    component: () => import('../views/setting/Setting.vue'),
  },
]

export const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {

  const lineStore = useLineStore()
  if (!lineStore.getPath) {
    const device = new DeviceDetector()
    const deviceInfo = device.parse(navigator.userAgent)
    const type = deviceInfo.device.type
    await initRoutes(type, lineStore)
    next({
      ...to, // 无限访问目标路由, 直到 addRoute() 添加完成
      replace: true, // 本次操作后，不能通过浏览器后退按钮，返回前一个路由
    })
  } else {
    if (to.matched.length < 1) {
      return next({path: '/404'})
    } else {
      let title = to.meta.title
      if (to !== undefined) {
        window.document.title = title
      }

      next()
    }
  }

})

router.afterEach((to, from) => {

})

const initRoutes = async (type, lineStore) => {

  if (type === 'desktop') {
    router.addRoute({
      path: '/',
      name: "Index",
      meta: {title: "Time-Line",transition: 'slide-left'},
      component: components[`../views/PcIndex.vue`],
    })
  } else {
    router.addRoute({
      path: '/',
      name: "Index",
      meta: {title: "Time-Line", transition: 'slide-left'},
      component: components[`../views/Index.vue`],
    })
  }
  lineStore.updatePath(true)
}




